package
{
    import com.dusk.game.Debug;
    import com.dusk.game.Logger;
    import com.dusk.net.AssetBundle;
    import com.dusk.net.AssetManager;
    import com.dusk.net.AssetType;
    import com.dusk.net.NativeFile;
    import com.dusk.net.ServerConnect;
    import com.dusk.util.SystemUtil;
    import com.dusk.view.GameInfoReporter;
    import com.game.data.constant.ConfigConst;
    import com.game.event.GameEventType;
    import com.game.manager.EventManager;
    import com.game.manager.GameSceneManager;
    import com.game.manager.SoundManager;
    import com.game.manager.SubWindowManager;
    import com.game.manager.SettingManager;
    import com.game.view.layer.loadingBar.LoadingBar1;
    
    import config.Config;
    
    import flash.desktop.NativeApplication;
    import flash.display.MovieClip;
    import flash.display.StageDisplayState;
    import flash.display.StageScaleMode;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import flash.filesystem.File;
    import flash.geom.Point;
    import flash.text.Font;
    import flash.ui.Keyboard;
    
    {
        (function ():void
        {
            var MODE_DEBUG:Boolean = (function ():Boolean
            {
                CONFIG::DEBUG{
                    return true;
                }
                CONFIG::RELEASE{
                    return false;
                }
            })();
            var MODE_RELEASE:Boolean = (function ():Boolean
            {
                CONFIG::DEBUG{
                    return false;
                }
                CONFIG::RELEASE{
                    return true;
                }
            })();
            if (MODE_DEBUG == MODE_RELEASE)
            {
                throw (new Error("只能是 DEBUG 模式或者 RELEASE 模式！请检查编译参数！"));
            }
            trace("当前模式为：".concat(MODE_DEBUG ? "DEBUG模式" : "RELEASE模式"));
        })();
    }
    
    [SWF(frameRate="30", backgroundColor="#000000", width="940", height="590", scriptTimeLimit="5")]
    public class GMain extends MovieClip
    {
        private static var _instance:GMain;
        
        public static function getIns():GMain
        {
            return _instance;
        }
        
        public function GMain()
        {
            super();
            _instance = this;
            if (!stage)
            {
                addEventListener(Event.ADDED_TO_STAGE, initGame);
            }
            else
            {
                initGame(new Event(Event.ADDED_TO_STAGE));
            }
        }
        
        private function initGame(param1:Event):void
        {
            if (hasEventListener(Event.ADDED_TO_STAGE))
            {
                removeEventListener(Event.ADDED_TO_STAGE, initGame);
            }
            loaderInfo.bytes.clear();
            stage.addEventListener(Event.ACTIVATE, onFocusChange);
            stage.addEventListener(Event.DEACTIVATE, onFocusChange);
            stage.addEventListener(KeyboardEvent.KEY_DOWN, keyFunc);
            stage.nativeWindow.title += " (" + ConfigConst.GAME_VERSION_NAME + ")";
            stage.nativeWindow.addEventListener(Event.CLOSE, onMainWindowClose);
            relocateWindow();
            initScene();
            initBaseInfo();
            var onLoadConfigDone:Function = function ():void
            {
                AssetManager.getIns().loadAssets(AssetBundle.getInGameLibs(), AssetType.SWF, null, startUp);
            }
            Config.getIns().configManager.loadConfig(onLoadConfigDone);
            
            
            CONFIG::DEBUG{
                //FlashTracerPreloader.initFlashTracer(stage);
                //MonsterDebugger.initialize(this);
                new Debug();
            }
        }
        
        private function startUp():void
        {
            Font.registerFont(AssetManager.getIns().getClass("font.FZCY") as Class);
            Font.registerFont(AssetManager.getIns().getClass("font.HKHB") as Class);
            var bar:LoadingBar1 = new LoadingBar1();
            GameSceneManager.getIns().addScene(bar);
            AssetManager.getIns().addCallback(bar.onComplete);
            AssetManager.getIns().loadAssets(AssetBundle.getInGameAssets(), AssetType.SWF, null, enterGame, bar.onProgress);
        }
        
        private function enterGame():void
        {
            Logger.logToFile("--------start game--------");
            Logger.logTime();
            GameSceneManager.getIns().switchScene(GameSceneManager.GAME_MENU);
        }
        
        /**
         * 重新定位窗口
         */
        public function relocateWindow():void
        {
            var p:Point = SystemUtil.getScreenResolution();
            var width:Number = stage.nativeWindow.width;
            var height:Number = stage.nativeWindow.height;
            stage.nativeWindow.x = ((p.x - width) * 0.5);
            stage.nativeWindow.y = ((p.y - height) * 0.5);
        }
        
        /**
         * 初始化设置信息、防沉迷、加速检测、服务器数据
         */
        private function initBaseInfo():void
        {
            //初始化游戏设置
            SettingManager.initGameSetting();
//			初始化防沉迷
//			setTimeout(NotificationManager.tellRest,1 * 3600 * 1000,1);
//			setTimeout(NotificationManager.tellRest,2 * 3600 * 1000,1);
            //初始化游戏数据
            (new Config()).initData();
            //初始化加速检测
//			HackChecker.enabledCheckSpeedUp();
            //初始化云端数据
//            ServerConnect.initData();
            SystemUtil.setIMEMode(SystemUtil.IME_HALF);
        }
        
        /**
         * 初始化游戏界面
         */
        private function initScene():void
        {
            tabChildren = false;
            tabEnabled = false;
            GameSceneManager.getIns().init(this);
            stage.scaleMode = StageScaleMode.SHOW_ALL;
            stage.addChild(new GameInfoReporter(0xFFFFFF, true, true, 0x00FF00));
        }
        
        /**
         * 窗口焦点改变
         * @param evt
         */
        private function onFocusChange(evt:Event):void
        {
            switch (evt.type)
            {
                case Event.ACTIVATE:
                    if (SettingManager.getSettingVO().isLostFocusPause)
                    {
                        EventManager.getIns().dispatchEvent(GameEventType.CONTINUE_GAME);
                    }
                    if (SettingManager.getSettingVO().isLostFocusMute)
                    {
                        SoundManager.openSnd();
                    }
                    break;
                case Event.DEACTIVATE:
                    if (SettingManager.getSettingVO().isLostFocusPause)
                    {
                        EventManager.getIns().dispatchEvent(GameEventType.PAUSE_GAME);
                    }
                    if (SettingManager.getSettingVO().isLostFocusMute)
                    {
                        SoundManager.closeSnd();
                    }
                    break;
            }
        }
        
        private function keyFunc(param1:KeyboardEvent):void
        {
            if (param1.keyCode == Keyboard.F11)
            {
                switch (stage.displayState)
                {
                    case StageDisplayState.FULL_SCREEN_INTERACTIVE:
                        stage.displayState = StageDisplayState.NORMAL;
                        SettingManager.getSettingVO().isFullScreen = false;
                        break;
                    case StageDisplayState.NORMAL:
                        if (stage.allowsFullScreen)
                        {
                            stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
                        }
                        SettingManager.getSettingVO().isFullScreen = true;
                        break;
                }
            }
            if (param1.keyCode == Keyboard.F5)
            {
                if (!SystemUtil.isApplication())
                {
                    return;
                }
                if (SystemUtil.isDebugger())
                {
                    throw "this function can' t run properly in debug mode";
                }
                NativeFile.start(File.applicationDirectory.resolvePath(ConfigConst.GAME_APP_NAME).nativePath);
                NativeApplication.nativeApplication.exit(0);
            }
        }
        
        private function onMainWindowClose(param1:Event):void
        {
            SubWindowManager.getIns().closeAllWindow();
            SettingManager.saveGameSettingWhenQuit();
            Logger.logTime();
            Logger.logToFile("--------exit game--------\n");
        }
    }
}